package com.game.hall;

import com.game.message.Msg;
import com.game.message.connetion.ConnectionManager;
import com.game.net.server.websocket.WebSocketFrameHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * Created by legend9999 on 2016/4/25.
 */
@Component
@ChannelHandler.Sharable
public class HallWSHandler extends WebSocketFrameHandler {
    private static Logger logger = LoggerFactory.getLogger(HallBiz.class);
    @Autowired
    private HallBiz hallBiz;

    public void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        if (frame instanceof TextWebSocketFrame) {
            // Send the uppercase string back.
            String request = ((TextWebSocketFrame) frame).text();
            logger.info("{} received {}", ctx.channel(), request);
            ctx.channel().writeAndFlush(new TextWebSocketFrame(request.toUpperCase(Locale.US)));
        } else if (frame instanceof WebSocketFrame) {
            ByteBuf content = frame.content();
            logger.info("I am WebSocketFrame , I can process byte message", content);
            int length = content.readInt();
            int msgId = content.readInt();
            int bodyLength = content.readableBytes();
            byte bodys [] = new byte[bodyLength];
            content.readBytes(bodys);
            Msg msg = new Msg();
            msg.setMsgId(msgId);
            msg.setBody(bodys);
            hallBiz.onMsg(msg, ctx);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        ctx.attr(ConnectionManager.connectTypeAttributeKey).set(true);
        ctx.attr(ConnectionManager.userIdAttributeKey).set(0);

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        ConnectionManager.getInstance().remove(ctx);
    }
}

